import {fetchWechatJsApiConfig} from '../api/wechat';
import wx from 'weixin-js-sdk';

const URL = window.location.href;
const APIS = ['scanQRCode'];

class WxApi {
    static api = null;

    static init(user) {
        WxApi.api = new WxApi(user);
    }

    _wx = wx;
    onWxReady = () => {
        console.log('WX READY!');
    };
    onWxError = err => {
        console.log('WX ERROR', err);
    };

    constructor(user) {
        const {merchantId} = user;
        const _this = this;
        this._wx.ready(this.onWxReady);
        this._wx.error(this.onWxError);
        fetchWechatJsApiConfig(merchantId, URL).then(res => {
            console.log('config WX with:', res);
            res.jsApiList = APIS;
            _this._wx.config(res);
        });
    }

    scanQrCode(options) {
        return this._wx.scanQRCode(options);
    }
}

export default WxApi;